Maddy Tabing

All blogs

Creating an API with Django REST Framework (Part 3  - - Documentation)

Now that we’ve set up our Django app, created an API, added token authentication to the API, and added the ability for users to view and regenerate their tokens, we can now generate some documentation for our users to view.

A huge benefit of Django REST Framework, is that not only does it include the token authentication, but it also has built-in API documentation. For this writeup, I’m just using the regular built-in documentation, however, DRF docs reference some great third party generators which look equally easy to set up.

To start, let’s install a few packages:

pip install markdown coreapi

We will also have to modify our settings.py again to tell DRF to use the built-in API schema:

REST_FRAMEWORK = {    
   'DEFAULT_AUTHENTICATION_CLASSES': [
      'rest_framework.authentication.TokenAuthentication',
   ],    
   'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema'
}

Next, let’s add an endpoint where the documentation will live. I chose api-docs/, but this is obviously up to you.

/urls.py

from django.urls import include, path 
from django.conf.urls import url 
from rest_framework.documentation import include_docs_urls

urlpatterns = [
   url(r'^api-docs/', include_docs_urls(title="Maddy's Test API", description="An API Powered by Django"))
]

Here the title and description will appear at the top of the page.

Revisiting our views — for this we’ll only look at a /users endpoint. Again, I opt to use function-based views and decorators, but you can also use class-based views. Under each method definition, you’ll notice comments delineating each method. These comments will appear as descriptions in your documentation. These should be as descriptive as possible.

Users will be able to GET, POST, DELETE using the /users endpoint so long as they provide their API key (detailed by the @permissions_classes decorator here).

from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework import parsers, renderers
from rest_framework.compat import coreapi, coreschema

@api_view(['GET', 'POST'])
@permissions_classes([IsAuthenticated,])
def users(request):
   """
   get: 
   Returns a list of app users.
   post:
   Creates a new instance of an app user.
   """
   if request.method == 'GET':
      ...
      data = # list of all users
   if request.method == 'POST':
      ...
      data = # newly created user
   return Response({"data" : data})

@api_view(['GET', 'DELETE'])
@permissions_classes([IsAuthenticated,])
def user(request, user_id):
   """
   get:
   Returns a specified app user.
 
   delete:
   Destroys specific app user.
   """
   if request.method == 'GET':
      ...
      data = # user data
   if request.method == 'DELETE':
      ...
      data = # message that user has been deleted 
   return Response({'data' : data})

Then our urls.py would look like:

from django.conf.urls import url 
from . import views 

urlpatterns = [
   url(r'^users/$', views.users),
   url(r'^users/<int: user_id>', views.user)
]

Now when we visit 127.0.0.1:800/api-docs/

The docs have been automatically generated! Moreover, with coreapi we can interact with our API via the CLI.

When you try to use the sandbox “Interact” the first time you’ll notice a response {“detail": “Authentication credentials were not provided."} Look familiar? To send our token along with our requests, at the bottom left corner we can add our token and then successfully make requests.

Success!

As mentioned, there are many third-party applications that you can also use to achieve the same with customization. You can further customize what your documentation and API look like by creating new schemas.

And there we have it! We have successfully:

  1. Created a django web application, giving users the ability to read their API tokens, and regenerate them.
  2. Created a usable API, protected by token authentication.
  3. Generated documentation to live on our django web app.

All of that just using Django’s Rest Framework!


Written by Maddy Tabing, Software Engineer